#!/bin/bash
#参考:http://linuxtoy.org/archives/chsdir.html
#参考:/etc/bash_completion

#用于保存覆盖之前的函数
#from http://mivok.net/2009/09/20/bashfunctionoverride.html
_py_save_function() {
    local ORIG_FUNC=$(declare -f $1)
    local NEWNAME_FUNC="$2${ORIG_FUNC#$1}"
    eval "$NEWNAME_FUNC"
}

#中文补齐函数

_py_completion()
{
    local IFS=$'\t\n' 
    local cur

#兼容旧版本的bash-completion
    test -z "`typeset -f _get_comp_words_by_ref`" && 
        cur=`_get_cword` ||
        _get_comp_words_by_ref cur

    _expand || return 0

    local dname bname tmp sep
    local -a rt
#目录名部分
    dname=$(dirname "$cur");
#文件名部分
    bname=$(basename "$cur");

#eval 用于消除转义符 例如 \[ 将变成 [ 
    eval dname=${dname}
    eval bname=${bname}

    test -z "$bname" && return 0;

    if [ "${dname}" = "/" ];then
        sep=""
    else
        sep="/"
    fi

    cd "$dname"

    if [ "$1" = "-d" ];then
        rt=(${rt[@]-} $(
        find . -maxdepth 1 -type d -print|cut -b 3-|pinyinmatch -f -c "$bname"|grep -v "^0"|cut -c 3-|while read -r tmp;do 
            printf '%s%s%s\n' "$dname" "$sep" "$tmp"
        done
        ))
    else
        rt=(${rt[@]-} $(
        find . -maxdepth 1 -print|cut -b 3-|pinyinmatch -f -c "$bname"|grep -v "^0"|cut -c 3-|while read -r tmp;do
            printf '%s%s%s\n' "$dname" "$sep" "$tmp"
        done
        ))
    fi
    
    COMPREPLY=( "${COMPREPLY[@]}" "${rt[@]}" )
}

_py_save_function _filedir _py_bak_filedir

_filedir()
{
    _py_bak_filedir $@
    _py_completion $@ 
}

_py_save_function _filedir_xspec _py_bak_filedir_xspec

_filedir_xspec ()
{
    _py_bak_filedir_xspec $@
    _py_completion $@ 
}

unset -f _py_save_function

